package com.zhouchb.stream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author Zhouchb
 * @Create 2021-11-2021/11/1 :21:50
 * @Description
 */
class haha{
    public static void main(String[] args) {
        client();
    }
    public static void client(){
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            InetAddress ia = InetAddress.getByName("127.0.0.1");
            socket = new Socket(ia,8848);
            outputStream = socket.getOutputStream();
            outputStream.write("你好！我是服务端".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        try {
            if (socket!=null)
                socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (outputStream!=null)
                outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
public class TCPTest {
    public static void main(String[] args) {
server();
//client();
    }

    public static void server(){
        ByteArrayOutputStream baos = null;
        ServerSocket serverSocket =null;
        Socket socket=null;
        InputStream inputStream = null;
        try {
           serverSocket = new ServerSocket(8848);
           socket = serverSocket.accept();
           inputStream = socket.getInputStream();
            byte[] buffer = new byte[5];
            baos = new ByteArrayOutputStream();
            int len;
            while ((len=inputStream.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos!=null)
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStream!=null)
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (serverSocket!=null)
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket!=null)
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("收到来自"+socket.getInetAddress().getHostName()+"消息");
        System.out.println(baos.toString());
    }
}
